#!/bin/bash

if [ "$#" -ne 6 ]; then
	echo "usage: $0 master port password sdk license n"
	exit
fi

master=$1
port=$2
password=$3
sdkfilename=$4
license=$5
n=$6

XEBIN="xe"

if [ "${port}" -eq "80" ]; then
	NOSSL="--nossl"
fi

XE="${XEBIN} -s ${master} -p ${port} -u root -pw ${password} ${NOSSL}"

echo "* Importing template VM"
VMTEMPLATE=`${XE} vm-import filename="${sdkfilename}"`

NETWORK=`${XE} network-list bridge=xenbr0 --minimal | head -n 1`


# add a VIF to the SDK VM
echo "* tweaking template SDK VM"
${XE} vif-create vm-uuid=${VMTEMPLATE} network-uuid=${NETWORK} device=0
${XE} vm-param-set uuid=${VMTEMPLATE} PV-args="noninteractive"
${XE} vm-param-set uuid=${VMTEMPLATE} memory-static-max=128MiB
${XE} vm-param-set uuid=${VMTEMPLATE} memory-static-min=128MiB
${XE} vm-param-set uuid=${VMTEMPLATE} memory-dynamic-max=128MiB
${XE} vm-param-set uuid=${VMTEMPLATE} memory-dynamic-min=128MiB

echo "* cloning VMS"
# clone the VM @n times
for i in `seq 1 ${n}`
do
	echo -n "	$i ... "
	vms[$i]=`${XE} vm-clone new-name-label="SDK xiu VM $i" uuid=${VMTEMPLATE}`
	echo "OK"
done

# start all VMs
echo "* starting VMS"
echo "	starting: template ${VMTEMPLATE}"
${XE} vm-start uuid=${VMTEMPLATE}

for vm in ${vms[@]}
do
	VM=${vms[$i]}
	echo "	starting: $vm"
	${XE} vm-start uuid=${vm}
done

# wait that all VMs are running
echo "* waiting VMS"

# make sure we got some time for having the guest agent writing all its necessary data
sleep 60

echo "* Applying license"
masterip=`${XE} vm-param-get --minimal uuid="${VMTEMPLATE}" param-name=networks | awk '{print $2}'`
echo "	Applying license to master (${masterip})"
${XEBIN} -s ${masterip} -p ${port} -u root -pw "xensource" ${NOSSL} \
	host-license-add license-file="${license}"

# get all ips and update a license to it
for vm in ${vms[@]}
do
	ip=`${XE} vm-param-get --minimal uuid="${vm}" param-name=networks | awk '{print $2}'`
	echo "	Applying license to ${vm} at IP (${ip})"
	
	${XEBIN} -s ${ip} -p ${port} -u root -pw "xensource" ${NOSSL} \
		host-license-add license-file="${license}"
done

sleep 40

echo "* Pooling all VMs to $masterip"

for vm in ${vms[@]}
do
	ip=`${XE} vm-param-get --minimal uuid="${vm}" param-name=networks | awk '{print $2}'`
	echo "	Pooling slave VM ${vm} to (${masterip})"

	${XEBIN} -s ${ip} -p ${port} -u root -pw "xensource" ${NOSSL} \
		pool-join master-address=${masterip} \
		master-username=root master-password=xensource master		

done
